<template>
    <!-- 一个按钮，点击后会打开导出数据的对话框 -->
    <el-button
      size="large"
      :icon="Download"
      circle
      @click="handleOpenExportModal"
    >
    </el-button>
    <!-- 一个对话框，用于导出数据 -->
    <el-dialog
      v-model="export_modal_data.dialog_visible"
      title="导出"
      width="512px"
    >
      <!-- 一个表单，用于收集导出设置 -->
      <el-form
        :model="export_modal_data.model_data"
        label-width="96px"
        size="large"
      >
        <!-- 表单项：导出文件名 -->
        <el-form-item label="导出文件名">
          <el-input v-model="export_modal_data.model_data.name" />
        </el-form-item>
        <!-- 表单项：导出列 -->
        <el-form-item label="导出列">
          <!-- 全选复选框 -->
          <el-checkbox
            v-model="export_modal_data.is_all"
            :indeterminate="export_modal_data.indeterminate"
            @change="handleCheckAllChange"
            label="全选"
          />
          <!-- 复选框组，用于选择导出的列 -->
          <el-checkbox-group
            v-model="export_modal_data.model_data.column"
            @change="handleColumnChange"
          >
            <el-checkbox
              :label="item.value"
              v-for="item in export_modal_data.columns"
              :key="item.key"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <!-- 表单项：筛选条件设置 -->
        <el-form-item label="筛选条件设置">
          <!-- 选择框，绑定到筛选条件 -->
          <el-select v-model="export_modal_data.model_data.condition">
            <el-option label="无条件" value="null"></el-option>
            <el-option label="使用当前条件" value="current"></el-option>
          </el-select>
        </el-form-item>
        <!-- 表单项：导出类型 -->
        <el-form-item label="导出类型">
          <el-select v-model="export_modal_data.model_data.type">
            <el-option label="当前页" value="page"></el-option>
            <el-option label="全部" value="all"></el-option>
          </el-select>
        </el-form-item>
        <!-- 表单项：操作按钮 -->
        <el-form-item>
          <el-button
            @click="export_modal_data.dialog_visible = false"
            :loading="export_modal_data.loading"
            size="large"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="handleExport"
            :loading="export_modal_data.loading"
            size="large"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </template>
  
  <script setup>
  // 导入下载图标
  import { Download } from "@element-plus/icons-vue";
  // 导入Vue的响应式引用
  import { ref } from "vue";
  // 导入xlsx库的写入和工具方法
  import { writeFile, utils } from "xlsx";
  // 导入文件保存器
  import { saveAs } from "file-saver";
  // 导入Element Plus的消息提示组件
  import { ElMessage } from "element-plus";
  
  const props = defineProps({
    filename: {
      default: "",
      type: String,
    },
    // 字段数据
    columns: {
      default: () => [],
      type: Array,
    },
    /**
     * 数据获取处理
     */
    handle: {
      default: null,
      type: Function,
    },
  });
  /**
   * 导出按钮
   *
   * 可选择字段
   * 可选择导出部分
   * 可选择导出全部
   */
  const export_modal_data = ref({
    dialog_visible: false,
    loading: false,
    columns: [],
    is_all: true,
    indeterminate: false,
    model_data: {
      column: [],
      type: "page",
      name: "",
      condition: "null",
    },
  });
  /**
   * 打开导出选择弹窗
   */
  const handleOpenExportModal = () => {
    export_modal_data.value.model_data = {
      column: props.columns.map((item) => item.value),
      type: "page",
      name: props.filename,
      condition: "null",
    };
    console.log(props.columns);
    export_modal_data.value.columns = props.columns;
    export_modal_data.value.dialog_visible = true;
    console.log(export_modal_data.value);
  };
  
  /**
   * 开始导出
   */
  const handleExport = async () => {
    export_modal_data.value.loading = true;
    let [success, list] = await props.handle({
      ...export_modal_data.value.model_data,
    });
  
    if (success) {
      // ElMessage.success("开始导出");
      try {
        handleCreateExportFile(list);
      } catch (error) {}
    } else {
      ElMessage.error("数据获取失败");
    }
    export_modal_data.value.loading = false;
  };
  
  /**
   * 导出文件
   */
  const handleCreateExportFile = (data_data) => {
    console.log(data_data);
    const filename = export_modal_data.value.model_data.name;
    let data = data_data.map((row) => {
      let obj = {};
      props.columns.forEach((value) => {
        if (export_modal_data.value.model_data.column.includes(value.value)) {
          obj[value.label] = value.handle
            ? value.handle(row[value.value], row)
            : row[value.value];
        }
      });
      return obj;
    });
    // 新建空workbook，然后加入worksheet
    const ws = utils.json_to_sheet(data);
    // 新建book
    const wb = utils.book_new();
    // 生成xlsx文件(book,sheet数据,sheet命名)
    utils.book_append_sheet(wb, ws, "工作簿1");
    // 写文件(book,xlsx文件名称)
    let blob = writeFile(wb, `${filename}.xlsx`);
    ElMessage.success("正在导出");
    saveAs(blob, `${filename}.xlsx`);
  };
  
  /**
   * 全选操作
   */
  const handleCheckAllChange = (val) => {
    export_modal_data.value.model_data.column = val
      ? props.columns.map((item) => {
          return item.value;
        })
      : [];
    export_modal_data.value.indeterminate = false;
  };
  /**
   * 字段选择
   */
  const handleColumnChange = (val) => {
    const checkedCount = val.length;
    export_modal_data.value.is_all = checkedCount === props.columns.length;
    export_modal_data.value.indeterminate =
      checkedCount > 0 && checkedCount < props.columns.length;
  };
  </script>
  
  <style lang="scss" scoped></style>